import React, { useContext, useEffect, useState } from "react";
import { Button, Menu, message, Modal, Tag } from "antd";
import { FileFolder } from "../../../component/filefolder";
import { File } from "../../../component/files";
import { FilefolderBtns } from "./filefolderbtns";
import { FolderOutlined, DeleteOutlined } from "@ant-design/icons";
import { apiMod, group } from "../vo/request";
import "./sider.less";
import { folder } from "../vo/vo";
import { KeyContext } from "./context";

type folderBindData = {
    apis: {
        aid: number;
        name: string;
        method: string;
        state: string;
    }[];
    fid: number;
    name: string;
}[]

const FILES: folderBindData = [
    {
        name: "公共分类",
        fid: 0,
        apis: []
    },
]


export function FileList() {
    const [files, setFiles] = useState(FILES);
    const projectId = sessionStorage.getItem("project");
    if (!projectId) {
        window.location.replace("/index/start");
    }

    useEffect(() => {
        const load = async () => {
            try {
                let res = await group.query(projectId as string);
                if (!res.code) {
                    let data = res.data as folder[];
                    let newData = data.map((value) => {
                        let apis = value.apis.map((value) => {
                            return {
                                aid: value.apiId,
                                name: value.apiName,
                                method: value.apiMethod,
                                state: value.apiStatus
                            }
                        });
                        return {
                            apis: apis,
                            fid: value.folderId,
                            name: value.folderName
                        }
                    });
                    setFiles(newData);
                }
            } catch (err) {
                console.log(err)
            }
        }
        load();
    }, [projectId])
    return (
        <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            className="api-menu"
        >
            <File data={{ name: "全部接口", aid: "allapi" }}>全部接口</File>
            {setFileFolders(files)}
        </Menu>
    )
}

function setFileFolders(files: folderBindData) {
    return files.map((value) => {
        return (
            <FileFolder
                key={value.fid}
                icon={
                    <FolderOutlined style={{ lineHeight: "40px", marginRight: 3 }}></FolderOutlined>
                }
                className="sider-menu-btn"
                childHeight={40}
                title={<TitleAndBtns title={value.name} id={value.fid} />}
            >
                {value.apis ? setFiles(value.apis) : ''}
            </FileFolder>
        )
    })
}

function setFiles(apis: Array<any>) {
    return apis.map((value) => {
        let data = {
            name: value.name,
            aid: "api" + value.aid,
            method: value.method,
            state: value.state
        };
        return <File key={value.aid} data={data} ><FileNameAndBtn data={data} title={value.name} /></File>
    })
}

function FileNameAndBtn(props: { title: string, data: any }) {
    const [show, setShow] = useState("none");
    const onMouseOver = () => {
        setShow("block");
    }
    const onMouseOut = () => {
        setShow("none");
    }
    let color = "processing";
    switch(props.data.state) {
        case "finish":
            color = "success";
            break;
        default: 
            break;
    }
    return (

        <div
            style={{
                display: "flex",
                justifyContent: "space-between",
            }}
            onMouseOver={onMouseOver}
            onMouseOut={onMouseOut}
        >
            <div>
                <Tag color={color}>{props.data.method}</Tag>
                <span>{props.title}</span>
            </div>

            <DeleteApi style={{ display: show }} id={props.data.aid} />
        </div>
    )
}

function DeleteApi(props: { id: string, style?: React.CSSProperties }) {
    const setSiderKey = useContext(KeyContext);
    const [isModalVisible, setModalVisible] = useState(false);
    const [isLoading, setLoading] = useState(false);
    const handleClick = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setModalVisible(true);
    }
    const handleCancel = (e: any) => {
        e.stopPropagation();
        setModalVisible(false);
    }
    const onDelete = async () => {
        let id = props.id.substring(3);
        try {
            setLoading(true);
            let res = await apiMod.delete(parseInt(id));
            setLoading(false);
            if (!res.code && res.data) {
                message.success(res.msg);
                setModalVisible(false);
                setSiderKey((key: any) => {
                    return key + 1;
                })
            } else {
                message.error(res.msg)
            }
        } catch (err) {
            console.log(err);
            setLoading(false);
        }
    }
    return (
        <div style={props.style}>
            <Button
                type="link"
                style={{ height: "auto", width: "auto", padding: 0, marginRight: 20 }}
                onClick={handleClick}
            >
                <DeleteOutlined />
            </Button>
            <div onClick={(e) => { e.stopPropagation(); }}>
                <Modal
                    title="删除接口"
                    visible={isModalVisible}
                    onCancel={handleCancel}
                    footer={[
                        <Button onClick={handleCancel} key="close">取消</Button>,
                        <Button onClick={onDelete} type="primary" key="submit" loading={isLoading}>提交</Button>
                    ]}
                    style={{ top: 300 }}
                >
                    确定要删除分类吗？此操作不可逆。
                </Modal>
            </div>

        </div>
    )
}



function TitleAndBtns(props: { title?: string, id: number }) {
    const [isShow, setShow] = useState(false);
    const onMouseOver = () => {
        setShow(true);
    }
    const onMouseOut = () => {
        setShow(false);
    }

    return (
        <div className="flex space-between" onMouseOver={onMouseOver} onMouseOut={onMouseOut}>
            <span>{props.title}</span>
            <FilefolderBtns className={isShow ? "" : "hide"} id={props.id} />
        </div>
    )
}